/*
 * @Author: huangyq
 * @Date: 2022-04-06 13:25:51
 * @LastEditTime: 2022-06-14 11:57:38
 * @LastEditors: huangyq
 * @Description: 错误处理函数
 * @FilePath: /vue3-boilerplate-pc-client/src/plugins/httpHelper/handler/ErrorHandler.ts
 */
import { ElMessage } from 'element-plus'
export interface IToastFunction {
  (message: string): Promise<unknown>
}

const errorCodes = {
  '000000': '系统错误'
}

const errorCodeMap = new Map<string, string>(Object.entries(errorCodes))

let toastNum = 0

/**
 * 构建错误处理函数
 * @param maxToastNum
 * @param errorCodes
 */
export function createErrorHandler() {
  const maxToast = 3
  const errorCodes = errorCodeMap || new Map()
  return (code: string, message: string) => {
    if (maxToast <= toastNum) return
    toastNum++
    const errMessage: string | undefined = errorCodes.has(code)
      ? errorCodes.get(code)
      : message

    ElMessage.error(errMessage || '系统错误')
    toastNum && toastNum--
  }
}
